package com.minshenglife.zanzan.service.impl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.minshenglife.zanzan.dao.RuleDao;
import com.minshenglife.zanzan.entity.Rule;
import com.minshenglife.zanzan.pub.Keys;
import com.minshenglife.zanzan.result.RuleHelp;
import com.minshenglife.zanzan.service.RuleService;


/**
 * 规则service
 * @author huodd
 *
 */
@Component
@Transactional
public class RuleServiceImpl  implements RuleService {
	Logger log = LoggerFactory.getLogger(RuleServiceImpl.class);
	
	@Resource
	RuleDao ruleDao;

	@Override
	@Transactional(readOnly=true)
	public Rule getFirstValidRule(String ruleType) {
		log.info("start getFirstValidRule()");
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("ruleType",ruleType);
		Rule rule=ruleDao.getFirstValidRule(map);
		return rule;
	}

	@Override
	public Long getCanTucaoNumByRule(Long canTucaoNum) {
		log.info("start getCanTucaoNumByRule()");
		if(canTucaoNum==null)
			canTucaoNum=new Long(0);
		try {
			Rule tucaoRule=getFirstValidRule(Keys.RULE_TYPE_TUCAO);
			if(tucaoRule != null ){
				if(Keys.RULE_LIMITTYPE_NUMBER.equals(tucaoRule.getLimitType())){
					canTucaoNum+=Long.parseLong(tucaoRule.getLimitNum());
				}else if(Keys.RULE_LIMITTYPE_TIMERANGE.equals(tucaoRule.getLimitType())){
					canTucaoNum=new Long(-1);//-1标识不限制
				}
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return canTucaoNum;
	}

	@Override
	public RuleHelp getCanSendFlowerNumByRule(Integer canSendFlowerNum) {
		log.info("start getCanSendFlowerNumByRule()");
		RuleHelp rh=new RuleHelp();
		Integer todayDefualtNum=2;//默认可送两朵
		if(canSendFlowerNum==null)
			canSendFlowerNum=0;
		try {
			Rule flowerRule=getFirstValidRule(Keys.RULE_TYPE_SENDFLOWER);
			if(flowerRule != null ){
				if(Keys.RULE_LIMITTYPE_NUMBER.equals(flowerRule.getLimitType())){
					canSendFlowerNum+=Integer.valueOf(flowerRule.getLimitNum());
				}else if(Keys.RULE_LIMITTYPE_TIMERANGE.equals(flowerRule.getLimitType())){
					canSendFlowerNum=-1;//-1标识不限制
				}
				//如果规则的开始时间与结束时间是同一天，则添加到返回对象中
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				if(sdf.format(flowerRule.getRuleStartTime()).equals(sdf.format(flowerRule.getRuleEndTime()))){
					rh.setRuleStartTime(flowerRule.getRuleStartTime());
					rh.setRuleEndTime(flowerRule.getRuleEndTime());
					log.debug("规则的开始时间与结束时间是同一天，将开始结束时间添加到返回对象中");
				}
			}else{
				canSendFlowerNum+=todayDefualtNum;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
			log.info("获取可送花数出现异常，返回可送花数+今天默认可送花数");
			canSendFlowerNum+=todayDefualtNum;
		}
		rh.setCanSendFlowerNum(canSendFlowerNum);
		return rh;
	}
}
